<template>
  <div id="apply">
    <!-- 头部 -->
    <div class="apply-h">
      <div class="item">
        <div class="nav active">提交资料</div>
        <div class="icon-arrow"></div>
      </div>
      <div class="item">
        <div class="nav active">支付年会员费</div>
        <div class="icon-arrow"></div>
      </div>
      <div class="item">
        <div class="nav">升级成功</div>
      </div>
    </div>
    <!-- 主体内容 -->
    <div class="apply-b">
      <span class="title">采购商会员支付</span>
      <span class="goBtn" @click="onRouteBack">返回</span>
      <div style="clear:both;"></div>
      <div class="apply-b-c">
        <div class="form-row">
          <span>购买年限</span>
            <select class="input-w" v-model="priceId">
              <option value="" v-for="(item, index) in priceList" :key="index" :value="item.id">{{item.title}}</option>
            </select>
        </div>
        <div class="form-row">
          <span>年费:</span>
          <span style="color:#F00384">{{showPrice}}元</span>
        </div>
        <dl class="payment-type">
          <dt>支付方式:</dt>
          <dd class="select">
            <!-- 中金 -->
            <w-radio v-model="txCode" label="1312" name="txCode" v-if="isTest">
              <i class="ico-zhongjin"></i>
            </w-radio>
            <w-radio v-model="txCode" label="20" name="txCode" v-if="isTest">
              <i class="ico-zhifubao"></i>
            </w-radio>
            <w-radio v-model="txCode" label="10" name="txCode" v-if="isTest">
              <i class="ico-weixin"></i>
            </w-radio>
           <!-- 微信支付（原生） -->
          <!-- <w-radio v-model="txCode" label="40" name="txCode" v-if="!isTest">
            <i class="ico-weixin"></i>
          </w-radio> -->
          <!-- 支付宝（原生） -->
          <!-- <w-radio v-model="txCode" label="50" name="txCode" v-if="!isTest">
            <i class="ico-zhifubao"></i>
          </w-radio> -->
          </dd>
        </dl>
      </div>
      <div class="apply-foot">
        <div class="nextBtn" @click="onPayment">下一步</div>
      </div>
    </div>
    <!-- 支付结果弹框 -->
    <div class="g-pay-result-pop" v-if="isPayResultPop">
      <div class="pay-result-pop">
        <div class="hd clearfix">
          <span class="tit fl">付款遇到问题？</span>  
          <i class="fr iconfont ico-close" @click="onPayError"></i>  
        </div>
        <div class="bd">
          <p class="ct">付款完成前请不要关闭此窗口。完成付款后请根据情况点击下面按钮：</p>
        </div>
        <div class="ft">
          <w-button type="default" @on-click="onPayError">支付遇到问题</w-button>
          <w-button type="main" @on-click="onPaySuccess">已完成付款</w-button>
        </div>
      </div>
    </div>
    <!-- 当订单支付成功时，发送表单数据 -->
    <form id="payForm" name="payForm" target="_blank" :action="paymentInfo.action" method="post" v-if="paymentInfo.action">
       <input type="hidden" name="message" :value="paymentInfo.message">
       <input type="hidden" name="signature" :value="paymentInfo.signature">
       <input type="hidden" name="txCode" :value="paymentInfo.txCode">
    </form>
    <!-- 支付结果弹框 -->
    <div class="g-pay-result-pop" v-if="isPayResultPop">
      <div class="pay-result-pop">
        <div class="hd clearfix">
          <span class="tit fl">付款遇到问题？</span>  
          <i class="fr iconfont ico-close" @click="onPayError"></i>  
        </div>
        <div class="bd">
          <p class="ct">付款完成前请不要关闭此窗口。完成付款后请根据情况点击下面按钮：</p>
        </div>
        <div class="ft">
          <w-button type="default" @on-click="onPayError">支付遇到问题</w-button>
          <w-button type="main" @on-click="onPaySuccess">已完成付款</w-button>
        </div>
      </div>
    </div>
    <div v-html="data.orderString" id="formID">
      {{data.orderString}}
    </div>
  </div>
</template>

<script>
  import { apiApplyRoleFee, apiIncrementPay, apiApplyIncrementPay } from 'js/api'
  import { mapGetters } from 'vuex'

  export default {
    data() {
      return {
        priceList: [],
        txCode: '1312',
        priceId: '',
        applyId: '',
        paymentInfo: {},
        isPayResultPop: false,
        data: {},
        isTest: true // 测试专用
      }
    },
    created() {
      const enterType = this.$route.query.type
      this.applyId = this.$route.query.id
      if (!enterType || !this.applyId) {
        this.$toast('缺少参数', () => {
          this.$router.push('/my/extra')
        })
        return
      }
      apiApplyRoleFee(this.token, enterType).then(data => {
        if (data.list && data.list.length) {
          this.priceList = data.list
          this.priceId = this.priceList[0].id
          // 加载中金的信息
          this.getPaymentInfoAndPay(true)
        }
      })
      // 测试专用
      if (decodeURIComponent(this.$route.query.test || '') == 'zhongjin') {
        this.isTest = false
      }
    },
    methods: {
      onRouteBack() {
        this.$router.go(-1)
      },

      /**
       * 点击了去支付（下一步）按钮
       */
      onPayment() {
        // 如果当前是微信支付（原生）
        if (this.txCode == 40) {
          this.getWeixin('wxpay')
          return
        }
        // 如果当前是原生支付宝支付（原生）
        if (this.txCode == 50) {
          this.getWeixin('alipay')
          return
        }
        // 如果是原生的中金支付
        if (this.txCode == 1312) {
          // 展示支付成功或失败提示页面
          this.isPayResultPop = true
          // 提交form表单数据
          document.payForm.submit()
          return
        }
        // 如果是中金的支付宝或微信支付
        this.getPaymentInfoAndPay()
      },

      /**
       * 获取支付信息；如果是中金支付的微信或支付宝，则直接支付；如果是中金支付，则获取数据
       *
       * @param { Boolean } isFirstIn 是否是第一次打开此方法
       */
      getPaymentInfoAndPay(isFirstIn = false) {
        // 支付方法code编码
        const txCode = this.txCode == '1312' ? '1312' : '1401'
        const paymentWay = this.txCode == '1312' ? null : this.txCode

        // 初始化新窗口对象
        let paymentWin = ''

        // 如果是第一次进入（获取中金的支付信息）
        if (!isFirstIn) {
          paymentWin = window.open()
        }

        // 调用获取支付信息接口
        apiIncrementPay(this.token, this.applyId, this.priceId, txCode, paymentWay, this.$route.query.status).then(data => {
          // 微信，支付宝支付
          if (data.imageUrl) {
            this.$toast('正在提交支付', () => {
              // 新窗口打开图片链接
              paymentWin.location = data.imageUrl
              // 展示支付成功或失败提示页面
              this.isPayResultPop = true
            })
          // 中金支付
          } else {
            // 将中金支付的支付信息保存下来
            this.paymentInfo = data
          }
        })
      },

      /**
       * 支付失败
       */
      onPayError() {
        this._curPayStatus()
      },

      /**
       * 支付成功
       */
      onPaySuccess() {
        this._curPayStatus()
      },
      getWeixin(type) {
        let _this = this
        let wd = window.open('/loading')
        apiApplyIncrementPay(this.token, this.applyId, this.priceId, type, this.$route.query.status).then((data) => {
          // 保存url链接
          localStorage.setItem('url', data.code_url)

          // 将用户信息保存到localStorage中
          localStorage.setItem('userInfo', JSON.stringify(this.$store.getters.userInfo))

          // 如果当前是微信支付
          if (type == 'wxpay') {
            this.isPayResultPop = true
            wd.location.href = (`/pay/weixin`)
          } else {
            this.data = data
          }
          setTimeout(() => {
            _this.$spin.hide()
          }, 3000)
        })
      },
      // 判断支付结果
      _curPayStatus() {
        const _this = this
        this.$store.dispatch('fetchApplyRoleInfo', {
          token: this.token,
          callback(data) {
            if (data.status == 'success') {
              _this.$router.push('/my/extra/paySuccess')
            } else {
              _this.isPayResultPop = false
            }
          }
        })
      }
    },
    computed: {
      ...mapGetters(['token']),
      showPrice() {
        let price = ''
        this.priceList.forEach(item => {
          if (item.id === this.priceId) {
            price = item.price
          }
        })
        return price
      }
    }
  }
</script>

<style lang="scss" scoped>
  .apply-h {
    height: 60px;
    background-color: #fff;
    padding: 10px 60px;
    margin-bottom: 10px;
  }

  .item {
    margin-left: 35px;
    display: inline-block;
  }

  .active {
    background-color: #F00384 !important;
    color: #fff !important;
  }

  .nav {
    width: 160px;
    height: 40px;
    background-color: #ddd;
    color: #999;
    border-radius: 6px;
    display: inline-block;
    line-height: 40px;
    text-align: center;
  }

  .icon-arrow {
    display: inline-block;
    width: 12px;
    height: 24px;
    vertical-align: middle;
    margin-left: 35px;
    background: url('../../assets/ico-arrow-right1.png') no-repeat 0 0;
  }

  .apply-b {
    height: 389px;
    background-color: #fff;
    padding: 20px;
    .title {
      color: #666;
    }
    .goBtn {
      height: 28px;
      border: 1px solid;
      color: #F00384;
      line-height: 28px;
      text-align: center;
      padding: 0 20px;
      float: right;
      cursor: pointer;
    }
    &-c {
      height: 241px;
      border: 1px solid #ddd;
      margin-top: 14px;
      padding: 25px 60px;
      input {
        border: 1px solid #ddd;
        height: 22px;
      }
      .form-row {
        margin-bottom: 37px;
      }
    }
  }
  select{
    border: 1px solid #ddd;
    height: 22px;
    line-height: 22px;
    color: #666;
    width: 120px;
  }

  .nextBtn {
    width: 160px;
    height: 38px;
    line-height: 38px;
    background-color: #F10180;
    color: #FFF;
    text-align: center;
    float: right;
    cursor: pointer;
  }

  .apply-foot {
    margin-top: 20px;
    .tit {
      display: inline-block;
      vertical-align: middle;
      height: 38px;
      line-height: 38px;
      margin-right: 40px;
      input {
        vertical-align: middle;
      }
    }
  }

  .payment-type {
    dt {
      font-size: 16px;
    }
    .select {
      margin-left: 80px;
      label {
        margin-right: 49px;
        &:last-child {
          margin-right: 0;
        }
      }
      i {
        display: inline-block;
        width: 71px;
        height: 71px;
        vertical-align: middle;
      }
      .ico-zhongjin {
        background-image: url('../../assets/payment/zhongjin.png');
        background-size: contain;
      }
      .ico-zhifubao {
        background-image: url('../../assets/payment/zhifubao.png') ;
        background-size: contain;
      }
      .ico-weixin {
        background-image: url('../../assets/payment/weixin.png');
        background-size: contain;
      }
      .ico-yinlian {
        background-image: url('../../assets/payment/yinlian.png');
        background-size: contain;
      }
    }
  }

  .g-pay-result-pop {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    background: rgba(0, 0, 0, .3);
  }
  .pay-result-pop {
    position: fixed;
    top: 50%;
    left: 50%;
    width: 550px;
    height: 190px;
    margin-left: -275px;
    margin-top: -95px;
    padding: 20px 38px;
    background: #fff;
    color: #666;
    .hd {
      padding: 10px 0;
      border-bottom: 1px solid #ddd;
      .tit {
        font-size: 16px;
      }
      .ico-close {
        cursor: pointer;
      }
    }
    .bd {
      padding: 20px 0;
    }
    .ft {
      padding-top: 20px;
      text-align: center;
      .default {
        margin-right: 38px;
      }
      .btn {
        height: 28px;
      }
    }
  }
</style>